const { studentsModel } = require('../models/studentsModels')
const { moveFiles, deleteFiles } = require('../utils/handleFiles');

//获取学员数据
async function getStudents(req, res, next) {
  const data = req.query;
  let result = "";
  // console.log('data:', data);
  //搜索全部数据
  result = await studentsModel.find(data)
  console.log(result);
  res.send({
    message: '获取学生数据成功！',
    code: 200,
    data: { result }
  })
}

//新增学员
async function addStudents(req, res, next) {
  //可以嵌套一个异常处理机制
  const data = req.body;
  if(data.images){
      const filename=path.basename(data.images);
      //处理图片
      moveFiles({
          fromPath:'./public/temp',
          toPath: './public/images',
          filename
      });
      deleteFiles('./public/temp');
      data.images='./images/'+filename;
  }
  const result = await studentsModel.create(data);
  res.send({
      code: 200,
      message: '学生数据新增成功'
  })
}

//修改学员
async function updateStudents(req, res) {
  const data = req.body;
  console.log(data);
  const result = await studentsModel.updateOne({ _id: data._id }, data);
  if (result) {
      res.send({
          message: '修改学生成功',
          code: 200,
          data: result
      })
  }
}






module.exports = {
  getStudents,addStudents,updateStudents
}